package com.example.shopping_web_back.interceptor;

import com.example.shopping_web_back.utils.JwtUtil;
import com.example.shopping_web_back.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class GlobalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Handler) throws Exception {
        //令牌验证
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true; // 放行 OPTIONS 请求
        }
        String token = request.getHeader("Customer");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal里面
            ThreadLocalUtil.set(claims);
            //成功，放行
            return true;
        } catch (Exception e) {
            //http状态响应码为401
            response.setStatus(401);
            //失败，不放行
            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //情况ThreadLocal的数据
        ThreadLocalUtil.remove();
    }
}
